package com.peach.springbootdemo.demo.web;

import com.peach.springbootdemo.demo.model.Demo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @date 2019-07-27
 * @author peach
 */
@RestController
public class DemoController {



    @RequestMapping("/demo")
    public String demo(HttpServletRequest request){
        //启动后访问 http://127.0.0.1:8080/demo?name=程序员

        String name = request.getParameter("name");

        return "hello spring boot, 我是" + name;
    }

    @RequestMapping(value="/getDemo", method = RequestMethod.POST)
    public Demo getDemo(){
        Demo demo = new Demo();
        demo.setCode("demo001");
        demo.setName("测试");
        demo.setAge(20);
        return  demo;
    }


    /*@PostMapping("/getDemo")
    public Demo getDemo(){
        Demo demo = new Demo();
        demo.setCode("demo001");
        demo.setName("测试");
        demo.setAge(20);
        return  demo;
    }*/

    //@PostMapping("/getDemos")
    @RequestMapping(value="/getDemos", method = RequestMethod.POST)
    public List<Demo> getDemos(){
        List<Demo> demos = new ArrayList<>();
        Demo demo1 = new Demo();
        demo1.setCode("demo001");
        demo1.setName("测试");
        demo1.setAge(20);
        demos.add(demo1);

        Demo demo2 = new Demo();
        demo2.setCode("demo001");
        demo2.setName("测试");
        demo2.setAge(20);
        demos.add(demo2);


        return  demos;
    }


    @RequestMapping(value="get/{name}", method=RequestMethod.GET)
    public String get(@PathVariable String name) {
        //http://localhost:8080/get/test   返回test
        return name;
    }



    @RequestMapping("/saveDemo")
    public void saveUser(@Valid Demo demo, BindingResult result) {
        System.out.println("demo:"+demo);
        if(result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
            }
        }
    }



}
